#!/bin/bash
# This is a template file to execute remote machine.

# python version is random on each VM
export PATH=$PATH:/usr/local/bin:/Users/bokken/Library/Python/3.7/bin:/Users/bokken/Library/Python/3.8/bin
export ARTIFACT_DIR=${PWD}/test-results

# TEST_TARGET = `ios` or `macos`
# TEST_PLATFORM = `editmode` or `playmode` or `standalone`
# SCRIPTING_BACKEND = `il2cpp` or `mono`
additional_component_arg="-c editor"
platform=Editor
architecture=${TEST_ARCHITECTURE}
suite=playmode

if [ ${TEST_PLATFORM} = "standalone" ]
then
  if [ ${TEST_TARGET} = "ios" ]
  then
    additional_component_arg="-c editor -c iOS"
    architecture=arm64
    platform=iOS
  elif [ ${TEST_TARGET} = "iossimulator" ]
  then
    additional_component_arg="-c editor -c iOS"
    platform=iOS
  elif [ ${TEST_TARGET} = "macos" ]
  then
    platform=StandaloneOSX
    if [ ${SCRIPTING_BACKEND} = "il2cpp" ]
    then
      additional_component_arg="-c editor -c StandaloneSupport-IL2CPP"
    else
      additional_component_arg="-c editor -c StandaloneSupport-Mono"
    fi
  fi
fi

if [ ${TEST_PLATFORM} = "editmode" ]
then
  suite=editor
fi

# workaround: upgrade pip
python3 -m pip install --upgrade pip

# install unity-downloader-cli
pip3 install unity-downloader-cli                                                     \
  --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple \
  --no-use-pep517                                                                     \
  --upgrade                                                                           \
  --user

# install utr
curl -s https://artifactory.prd.it.unity3d.com/artifactory/unity-tools/utr-standalone/utr \
  --output utr
chmod +x ./utr

# Install Rosetta when architecture is x64 and device is Apple Silicon
if [ ${TEST_TARGET} = "macos" ] && [ ${architecture} = "x64" ] && [ `uname -m` == "arm64" ]
then
  # install rosetta 2
  softwareupdate --install-rosetta --agree-to-license
fi

if [ ${TEST_PLATFORM} = "standalone" ]
then
  # run utr
  ./utr \
    --suite=${suite} \
    --platform=${platform} \
    --player-load-path=${PLAYER_LOAD_PATH} \
    --artifacts_path=${ARTIFACT_DIR} \
    --architecture=${architecture} \
    --player-connection-ip=${BOKKEN_DEVICE_IP}
  result=$?
else
  # download unity editor
  unity-downloader-cli \
    -u ${EDITOR_VERSION} \
    ${additional_component_arg} \
    --wait \
    --published

  # run utr
  ./utr \
    --suite=${suite} \
    --platform=${platform} \
    --scripting-backend=${SCRIPTING_BACKEND} \
    --extra-editor-arg="-${EXTRA_EDITOR_ARG}" \
    --testproject=${HOME}/${TEST_PROJECT_DIR} \
    --editor-location=${HOME}/.Editor \
    --artifacts_path=${ARTIFACT_DIR} \
    --architecture=${architecture}
  result=$?
fi

# return exit-code
exit $result